<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Exception;
use Illuminate\Http\Request;

class VerificationTokenMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
     */
    public function handle(Request $request, Closure $next)
    {
        if ($request->hasHeader('token')) {
            try {
                $usertoken = decrypt($request->header('token'));
                $request->USER_ID = $usertoken['id'];
                $user = User::query()->find($usertoken['id']);
                if (! $user) {
                    return responses('TOKEN USER IS ERROR', 101);
                }
                if (env('TOKEN_EXP_HOUR', 0) > 0) {
                    $time = $usertoken['time'];
                    if ((time() - $time) > env('TOKEN_EXP_HOUR') * 3600) {
                        return responses('INVALID TOKEN EXPIRED', 101);
                    }
                }
//                if(!isset($usertoken['session_key'])){
//                    return responses('INVALID TOKEN EXPIRED',101);
//                }
//                $request->SESSION_KEY =  $usertoken['session_key'];
                return $next($request);
            } catch (Exception $exception) {
                return responses('INVALID TOKEN PARSING ERROR', 101);
            }
        } else {
            return responses('INVALID TOKEN', 101);
        }
    }
}
